package com.test.znb.AOP;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * AOP统一切面 
 * 
 * @author kk
 *
 */
@Aspect
@Component
public class AOP_znb {
	
	private Logger logger=Logger.getLogger(getClass());
	
	ThreadLocal<Long> startTime = new ThreadLocal<>();
	/*
	 * 切点znb.controller记录访问request & response
	 * 写入日志
	 */
	@Pointcut("execution(public * com.test.znb.controller..*.*(..))")
	public void znbcontroller() {}
	@Before("znbcontroller()")
	public void doBefore(JoinPoint jp) throws Throwable{
		startTime.set(System.currentTimeMillis());
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();	
		logger.info("CLASS_METHOD : " + jp.getSignature().getDeclaringTypeName() + "." + jp.getSignature().getName());
		logger.info("ARGS : " + Arrays.toString(jp.getArgs()));
	}
	@AfterReturning(returning="ret",pointcut="znbcontroller()")
	public void AfterReturning(Object ret) throws Throwable{
		 logger.info("RESPONSE : " + ret);
	     logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
	}
	
}
